package cn.hh.wechatkit.api.card;

import cn.hh.wechatkit.data.returndata.Meta_RMsg_Base;
import cn.hh.wechatkit.data.postdata.card.Meta_CardConsumeTicketPostData;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;

import java.io.IOException;
import static cn.hh.wechatkit.helper.WxConst.ConsumeTicket_Post_URL;


/**
 * Created this one by HMH on 2017/5/7.
 */
@Slf4j
public class WxAPI_Card_Consume_Api {
    //日志

    /**
     * 核销卡券
     * @param code 卡券code
     * @param ACCESS_TOKEN 基础令牌
     * @return 返回消息
     * @throws Wx_Exception_InvalidResponse 响应异常
     */
    public static Meta_RMsg_Base consume(String code, String ACCESS_TOKEN) throws Wx_Exception_InvalidResponse {
        String url = ConsumeTicket_Post_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
        Meta_CardConsumeTicketPostData postData = new Meta_CardConsumeTicketPostData();
        postData.setCode(code);
        Response response = null;
        try {
            response = httpUtil.postJson(url, postData);
            //获取数据
            if (response != null) {
                try {
                    String body = response.body().string();
                    return JSON.parseObject(body, Meta_RMsg_Base.class);
                } catch (IOException e) {
                    log.error(" ==> json解析出错");
                    throw new Wx_Exception_InvalidJsonParse("json解析出错", e);
                }
            }
            log.error(" ==> 校验卡券接口，请求失败");
            throw new Wx_Exception_InvalidResponse("请求失败");
        } catch (IOException e) {
            log.error(" ==> 校验卡券出错", e);
            throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错", e);
        }
    }

}
